package com.szp.pgyer

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.FileProvider
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class DownLoadApp(var context: Context) {

    companion object {
        private const val TAG = "DownLoadApp"
    }

    //apk下载路径
    val PATH_UPDATE_APK = context.filesDir.absolutePath + File.separator + "update"

    val notificationManager =
        context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    var notification: Notification? = null

    val builder = NotificationCompat.Builder(context, "NOTIFICATION_CHANNEL_ID")

    /**
     * 创建下载文件夹
     */
    fun createDir() {
        val file = File(PATH_UPDATE_APK)
        if (!file.exists()) {
            file.mkdirs()
        }
    }

    /**
     * 创建下载安装文件
     */
    fun createFile(): File? {
        createDir()

        var file = File(PATH_UPDATE_APK, "update.apk")
        if (file.exists()) file.delete()
        try {
            file.createNewFile()
            return file
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 下载Apk
     */
    fun downloadApk(url: String) {
        val request = Request.Builder().url(url).build()
        OkHttpUtil.getOkHttpClient().newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.d(TAG, "onFailure: ${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {

                initNotification()

                response.body.let {
                    Log.d(TAG, "开始下载: ")
                    var inputStream: InputStream? = null
                    var fos: FileOutputStream? = null
                    var buff = ByteArray(2048)
                    var len = 0
                    var contentLength: Long = 0
                    var downloadLength: Long = 0

                    try {
                        inputStream = response.body?.byteStream()
                        val file = createFile()
                        fos = FileOutputStream(file)
                        val total = response.body?.contentLength()

                        contentLength = total ?: 0

                        var sum: Long = 0

                        while ((inputStream?.read(buff)!!.also { len = it }) != -1) {
                            fos.write(buff, 0, len)
                            sum += len
                            var progress = (sum * 1.0f / total!! * 100)
                            Log.d(TAG, "总大小: $contentLength  当前下载：  $downloadLength 进度 ：$progress")
                            updateNotification(progress.toInt())
                            downloadLength = sum
                        }
                        fos.flush()
                        file?.let { it1 -> downFinish(it1, downloadLength == contentLength) }
                    } catch (e: Exception) {
                        Log.d(TAG, "exception: ${e.message}")
                    } finally {
                        inputStream?.let { it.close() }
                        fos?.let { it.close() }
                    }
                }
            }
        })
    }

    /**
     * 初始化通知
     */
    private fun initNotification() {
        Log.d(TAG, "initNotification: 初始化信息中心!")

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "NOTIFICATION_CHANNEL_ID",
                "NOTIFICATION_CHANNEL_NAME",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(channel)
        }

        builder.setContentTitle("正在更新...") //设置通知标题
            .setWhen(System.currentTimeMillis())
            .setTicker("通知来了")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(
                BitmapFactory.decodeResource(
                    context.resources,
                    R.mipmap.ic_launcher
                )
            ) //设置通知的大图标
            //                .setDefaults(Notification.DEFAULT_ALL) //设置通知的提醒方式
            .setPriority(NotificationCompat.PRIORITY_DEFAULT) //设置通知的优先级：默认
            .setAutoCancel(false) //设置通知被点击一次是否自动取消
            .setContentText("下载进度:" + "0%")
            .setProgress(100, 0, false)
        notification = builder.build() //构建通知对象
    }

    /**
     * 更新消息栏
     */
    var tempProgress = 0

    private fun updateNotification(progress: Int) {
        if (progress - tempProgress < 1) return
        Log.d(TAG, "更新下载进度: $progress")
        builder.setProgress(100, progress, false)
        builder.setContentText("下载进度:$progress%")
        notification = builder.build()
        notificationManager.notify(1, notification)
        tempProgress = progress
    }

    /**
     * 下载结束
     */
    private fun downFinish(file: File, isDownloadSuccess: Boolean) {
        tempProgress = 0
        if (!isDownloadSuccess) {
            notificationManager.cancel(1)
            return
        }
        Log.d(TAG, "downSuccess: 下载完成")
        builder.setContentTitle("下载完成")
            .setContentText("点击安装")
            .setAutoCancel(true) //设置通知被点击一次是否自动取消
        val apkUri = FileProvider.getUriForFile(context, "com.szp.pgyer.fileprovider", file)
        val intent = Intent(Intent.ACTION_VIEW)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        //判断版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
        }
        val pi = PendingIntent.getActivity(context, 0, intent, 0)
        notification = builder.setContentIntent(pi).build()
        notificationManager.notify(1, notification)
    }
}





















